<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\RedisAdmin;
use app\RedisApi;
use think\Db;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function test()
    {
        $this->success('返回成功', $this->request->param());
    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {
        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

    public function cash_message1(){
        $appid = "wx9ec960dadf971791";
        $secret = "5d31e7dd4bc43f5701064dc2a936add7";
        $access_token_redis = RedisApi::getInstance()->hGet('applet_new_access_token',['expires_in','access_token']);  //判断access——tokens是否过期
        $today_time = date('Y-m-d');
        $data = [
            'info'=>$access_token_redis,
            'time'=>date('Y-m-d H:i:s'),
        ];
        //    file_put_contents("getAppletToke_".$today_time.".txt", json_encode($data). PHP_EOL, FILE_APPEND);
        if($access_token_redis['access_token']){
            $access_token_info = [
                'status_time'=>$access_token_redis['expires_in'],
                'access_token'=>$access_token_redis['access_token'],
            ];
            $access_token_info = json_encode($access_token_info);
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $token = $this->getJson($url);
            $get_access_token_result = json_decode($token, true);
//            $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
//            $get_access_token_result = httpCurl($access_token_url,'get');
            $today_time = date('Y-m-d');
            $data_log = [
                'sql'=>$get_access_token_result,
//                'appId'=>$appId,
//                'appSecret'=>$appSecret,
                'time'=>date('Y-m-d H:i:s'),
            ];
            //    file_put_contents("get_applet_access_token_".$today_time.".txt", json_encode($data_log). PHP_EOL, FILE_APPEND);
            $access_token_result = $get_access_token_result;
            if(isset($access_token_result['errcode'])){
                $this->error($access_token_result['errmsg']);
            }
            $access_token_info = [
                'status_time'=>$access_token_result['expires_in'],
                'access_token'=>$access_token_result['access_token'],
            ];
            $access_token_info = json_encode($access_token_info);
            RedisApi::getInstance()->hSet('applet_new_access_token',$access_token_result,$access_token_result['expires_in']);
        }
        $access_token_info = json_decode($access_token_info,true);
     //   var_dump($access_token_info);
        $uri ='https://api.weixin.qq.com/cgi-bin/message/template/send';
        $access_token = $access_token_info["access_token"];
//        $openid_all_arr = Db::name('gzh_openid')->group('id desc')->column('openid');
//      //  var_dump($openid_all_arr);
//        $next_openid = '';
//        if(isset($openid_all_arr[0])){
//            $next_openid = Db::name('gzh_openid')->where(['openid'=>$openid_all_arr[0]])->value('next_openid');
//        }
//        $uri = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&next_openid='.$next_openid;
        $uri = $uri.'?access_token='.$access_token;
      //  $parents_id = Db::name('student')->where(['id'=>$v])->value('parents_id');
        $student_name = Db::name('student')->where(['id'=>2])->value('student_name');
     //   $parent_id_arr = Db::name('parent_bind')->where(['student_id'=>$v])->column('parent_id');
        $openid = Db::name('gzh_openid')->where(['user_id'=>9])->value('openid');
        // $openid = Db::name('user')->where(['id'=>$vv])->value('openid');
        $data=  array('touser'=>$openid,   //发给谁
            'template_id'=>'RMsmKaedAfq2EINdeh_pJnS-dnFiNGx2LJWxYE2NKZI',   //模板id
            // 'url'=>'pages/index/index',     //这个是你发送了模板消息之后，当用户点击时跳转的连接
            'topcolor'=>"#FF0000",   //颜色
            'miniprogram'=>[ "appid"=>"wx8b97b45b7bddef4c",
                "pagepath"=>"pages/index/index"],
            'data'=>array(
                'first'=>array(
                    'value'=>'21212',
                    'color'=>'#173177'
                ),
                'keyword1'=>array(
                    'value'=>$student_name,
                    'color'=>'#173177'
                ),
                'keyword2'=>array(
                    'value'=>date('Y-m-d H:i:s'),
                    'color'=>'#173177'
                ),
                'keyword3'=>array(
                    'value'=>'323',
                    'color'=>'#173177'
                ),
                'keyword4'=>array(
                    'value'=>'323',
                    'color'=>'#173177'
                ),
//                                'remark'=>array(
//                                    'value'=>'已接到您的孩子',
//                                    'color'=>'#173177'
//                                )
            )
        );
        $res_data = $this->getJson($uri,$data);
        $res_data = json_decode($res_data, true);



//        $data=  array('touser'=>'oMXM8wRUXWlu6YUC8j2fWzZt5z8Q',   //发给谁
//            'template_id'=>'RMsmKaedAfq2EINdeh_pJnS-dnFiNGx2LJWxYE2NKZI',   //模板id
//           // 'url'=>'pages/index/index',     //这个是你发送了模板消息之后，当用户点击时跳转的连接
//            'topcolor'=>"#FF0000",   //颜色
//            'miniprogram'=>[ "appid"=>"wx8b97b45b7bddef4c",
//             "pagepath"=>"pages/index/index"],
//            'data'=>array(
//                'first'=>array(
//                    'value'=>'21212',
//                    'color'=>'#173177'
//                ),
//                'keyword1'=>array(
//                    'value'=>'已接到您的孩子',
//                    'color'=>'#173177'
//                ),
//                'keyword2'=>array(
//                    'value'=>'签到时间',
//                    'color'=>'#173177'
//                ),
//                'keyword3'=>array(
//                    'value'=>'签到时间',
//                    'color'=>'#173177'
//                ),
//                'keyword4'=>array(
//                    'value'=>'签到时间',
//                    'color'=>'#173177'
//                ),
//                'remark'=>array(
//                    'value'=>'已接到您的孩子',
//                    'color'=>'#173177'
//                )
//            )
//        );
//        $res_data = $this->getJson($uri,$data);
//        $res_data = json_decode($res_data, true);
//        if (isset($res_data['errcode']) && $res_data['errcode'] != 0) {
//            return false;
//        }
        $this->success('更新成功');
    }
    public function cash_message(){
        $appid = "wx9ec960dadf971791";
        $secret = "5d31e7dd4bc43f5701064dc2a936add7";
        $access_token_redis = RedisApi::getInstance()->hGet('applet_new_access_token',['expires_in','access_token']);  //判断access——tokens是否过期
        $today_time = date('Y-m-d');
        $data = [
            'info'=>$access_token_redis,
            'time'=>date('Y-m-d H:i:s'),
        ];
        //    file_put_contents("getAppletToke_".$today_time.".txt", json_encode($data). PHP_EOL, FILE_APPEND);
        if($access_token_redis['access_token']){
            $access_token_info = [
                'status_time'=>$access_token_redis['expires_in'],
                'access_token'=>$access_token_redis['access_token'],
            ];
            $access_token_info = json_encode($access_token_info);
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $token = $this->getJson($url);
            $get_access_token_result = json_decode($token, true);
//            $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
//            $get_access_token_result = httpCurl($access_token_url,'get');
            $today_time = date('Y-m-d');
            $data_log = [
                'sql'=>$get_access_token_result,
//                'appId'=>$appId,
//                'appSecret'=>$appSecret,
                'time'=>date('Y-m-d H:i:s'),
            ];
            //    file_put_contents("get_applet_access_token_".$today_time.".txt", json_encode($data_log). PHP_EOL, FILE_APPEND);
            $access_token_result = $get_access_token_result;
            if(isset($access_token_result['errcode'])){
                $this->error($access_token_result['errmsg']);
            }
            $access_token_info = [
                'status_time'=>$access_token_result['expires_in'],
                'access_token'=>$access_token_result['access_token'],
            ];
            $access_token_info = json_encode($access_token_info);
            RedisApi::getInstance()->hSet('applet_new_access_token',$access_token_result,$access_token_result['expires_in']);
        }
        $access_token_info = json_decode($access_token_info,true);
     //   var_dump($access_token_info);
        $uri ='https://api.weixin.qq.com/cgi-bin/message/template/send';
        $access_token = $access_token_info["access_token"];
        $openid_all_arr = Db::name('gzh_openid')->group('id desc')->column('openid');
      //  var_dump($openid_all_arr);
        $next_openid = '';
//        if(isset($openid_all_arr[0])){
//            $next_openid = Db::name('gzh_openid')->where(['openid'=>$openid_all_arr[0]])->value('next_openid');
//        }
        $uri = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&next_openid='.$next_openid;
      //  $uri = $uri.'?access_token='.$access_token;

//        $data=  array('touser'=>'oQq_44l02FMv5fOY5obH1xXTBp8I',   //发给谁
//            'template_id'=>'zu17BQAxYjUXYgReY5cVhbRX-2WrrJZIzphcFFACGLw',   //模板id
//            'url'=>'#',     //这个是你发送了模板消息之后，当用户点击时跳转的连接
//            'topcolor'=>"#FF0000",   //颜色
//            'miniprogram' => '',
//            'data'=>array(
//
//                'first'=>array(
//                    'value'=>'21212',
//                    'color'=>'#173177'
//                ),
//                'keyword1'=>array(
//                    'value'=>'2121',
//                    'color'=>'#173177'
//                ),
//                'keyword2'=>array(
//                    'value'=>'2121',
//                    'color'=>'#173177'
//                ),
//                'keyword3'=>array(
//                    'value'=>'21212',
//                    'color'=>'#173177'
//                ),
//                'keyword4'=>array(
//                    'value'=>'32',
//                    'color'=>'#173177'
//                ),
//                'remark'=>array(
//                    'value'=>'323',
//                    'color'=>'#173177'
//                )
//            )
//        );
        $data = [];
        $res_data = $this->getJson($uri,$data);
        $res_data = json_decode($res_data, true);
        if (isset($res_data['errcode']) && $res_data['errcode'] != 0) {
            return false;
        }else{
            var_dump($res_data);
            $openid_arr = $res_data['data']['openid'];
            $isnert_arr = [];
            foreach ($openid_arr as $w=>&$v){
                if(!isset($openid_all_arr[0]) ||  (isset($openid_all_arr[0]) && !in_array($v,$openid_all_arr))){
                    $isnert_arr[$w]['openid'] = $v;
                    $isnert_arr[$w]['create_time'] = time();
                    $isnert_arr[$w]['update_time'] = time();
                    $isnert_arr[$w]['next_openid'] = $res_data['next_openid'];
                }
            }
           // var_dump($isnert_arr);
            Db::name('gzh_openid')->insertAll($isnert_arr);
        }
        $this->success('更新成功');
    }

    public function getJson($url = '', $param = [] ,$contentType = 'json'){
        $ch = curl_init();
        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $url);
        // 请求参数类型
        $param = $contentType == 'json' ? urldecode(json_encode($param)) : http_build_query($param);
        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // post提交
        if($param){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }
        // 返回的数据是否自动显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 执行并接收响应结果
        $output = curl_exec($ch);
     //   var_dump($output);
        // 关闭curl
        curl_close($ch);
        return $output ;

    }

    public function get_unicode(){
        $appid = "wx9ec960dadf971791";
        $secret = "5d31e7dd4bc43f5701064dc2a936add7";
        $access_token_redis = RedisApi::getInstance()->hGet('applet_new_access_token',['expires_in','access_token']);  //判断access——tokens是否过期
        $today_time = date('Y-m-d');
        $data = [
            'info'=>$access_token_redis,
            'time'=>date('Y-m-d H:i:s'),
        ];
        //    file_put_contents("getAppletToke_".$today_time.".txt", json_encode($data). PHP_EOL, FILE_APPEND);
        if($access_token_redis['access_token']){
            $access_token_info = [
                'status_time'=>$access_token_redis['expires_in'],
                'access_token'=>$access_token_redis['access_token'],
            ];
            $access_token_info = json_encode($access_token_info);
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $token = $this->getJson($url);
            $get_access_token_result = json_decode($token, true);
//            $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
//            $get_access_token_result = httpCurl($access_token_url,'get');
            $today_time = date('Y-m-d');
            $data_log = [
                'sql'=>$get_access_token_result,
//                'appId'=>$appId,
//                'appSecret'=>$appSecret,
                'time'=>date('Y-m-d H:i:s'),
            ];
            //    file_put_contents("get_applet_access_token_".$today_time.".txt", json_encode($data_log). PHP_EOL, FILE_APPEND);
            $access_token_result = $get_access_token_result;
            if(isset($access_token_result['errcode'])){
                $this->error($access_token_result['errmsg']);
            }
            $access_token_info = [
                'status_time'=>$access_token_result['expires_in'],
                'access_token'=>$access_token_result['access_token'],
            ];
            $access_token_info = json_encode($access_token_info);
            RedisApi::getInstance()->hSet('applet_new_access_token',$access_token_result,$access_token_result['expires_in']);
        }
        $access_token_info = json_decode($access_token_info,true);
        //   var_dump($access_token_info);
        $uri ='https://api.weixin.qq.com/cgi-bin/message/template/send';
        $access_token = $access_token_info["access_token"];
        $openid_all_arr = Db::name('gzh_openid')->where(['is_update'=>0])->group('id desc')->limit(200)->column('openid');
        foreach ($openid_all_arr as $w=>$v){
            $uri = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$v;
            $data = [];
            $res_data = $this->getJson($uri,$data);
            $res_data = json_decode($res_data, true);
            if (isset($res_data['errcode']) && $res_data['errcode'] != 0) {
                continue;
            }else{
                $unicod = $res_data['unionid'];
                $user_id = Db::name('user')->where(['unionid'=>$unicod])->field('id')->find();
                $update = [
                    'unionid'=>$unicod,
                    'is_update'=>1,
                    'update_time'=>time(),
                ];
                if($user_id){
                    $update['user_id'] = $user_id['id'];
                    $update['is_update'] = 2;
                }
                Db::name('gzh_openid')->where(['openid'=>$res_data['openid']])->update($update);
//                $res = Db::name('user')->where(['unionid'=>$unicod])->update(['gzh_openid'=>$res_data['openid'],'updatetime'=>time()]);
//                if($res){
//
//                }
            }
        }

        $this->success('更新成功');
    }
}
